package org.jugile.util;

/*

Copyright (C) 2007-2011 Jukka Rahkonen  email: jukka.rahkonen@iki.fi

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

import java.util.ArrayList;
import java.util.List;

/**
 * "And Cush begat Nimrod: he began to be a mighty one in the earth.
 *  He was a mighty hunter before the LORD: wherefore it is said, 
 *  Even as Nimrod the mighty hunter before the LORD. 
 *  And the beginning of his kingdom was Babel, and Erech, and Accad, and Calneh, 
 *  in the land of Shinar. Out of that land went forth Asshur, and builded Nineveh, 
 *  and the city Rehoboth, and Calah And Resen between Nineveh and Calah: 
 *  the same is a great city." (Gen 10:8-12)
 *
 * ==========
 * 
 * @author jukka.rahkonen@iki.fi
 */
public class OoQuery extends Node {

	public OoQuery(String name) {
		super(name);
	}
	
	public OoQuery q(String q) { attr("q", q); return this; }
	public String q() { return attr("q"); }
	
	private int qpCount = 0;
	public OoQuery p(String p) { attr("qp"+(qpCount++), p); return this; }
	public List<String> params() {
		List<String> res = new ArrayList<String>();
		for (int i = 0; i < qpCount; i++) res.add(attr("qp"+i));
		return res;
	}
	
	public OoQuery order(String o) { attr("order", o); return this; }
	public String order() { return attr("order"); }

	public OoQuery add(String name) {
		OoQuery sub = new OoQuery(name);
		return (OoQuery)add(sub);
	}
	
	public OoQuery up() { return (OoQuery)super.up(); }

	public Node exec(Object d) {
		Node res = new Node(name());
		execute2(d, res);
		return res;
	}
	
	private void execute2(Object d, Node res) {
		Proxy p = doQuery(new Proxy(d));
		if (p != null && p.isList()) {
			for (Object item : p.getList()) {
				Node n = res.add(name());
				for (Node ch : children()) ((OoQuery)ch).execute2(item, n);
			}
			return;
		}
		if (!res.isRoot()) res = res.add(name());
		if (p == null) for (Node ch : children()) ((OoQuery)ch).execute2(d, res);
		else res.value(p.getObject());
	}

	private Proxy doQuery(Proxy d) {
		if (!empty(q())) return new Proxy(d.get(q())); 
		if (!hasChildren()) return new Proxy(d.get(name()));
		return null;
	}
	
}
